<template>
  <container-wrapper id="alertId"
    :designer="designer"
    :widget="widget"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList">
    <el-card :key="widget.id"
      ref="cardRef"
      class="card-container"
      @click.stop="selectWidget(widget)"
      :shadow="widget.options.shadow"
      :style="{width: widget.options.cardWidth + '!important' || ''}"
      :class="[selected ? 'selected' : '', !!widget.options.folded ? 'folded' : '', customClass]">
      <draggable :list="widget.widgetList"
        item-key="id"
        :group="{name: 'dragGroup', pull: (isInLayoutSync && isSyncFromLeft) ? 'clone' : true, put: !isSyncFromLeft}"
        :clone="(isInLayoutSync && isSyncFromLeft) ? handleClone : undefined"
        handle=".drag-handler"
        tag="transition-group"
        :component-data="{name: 'fade'}"
        ghost-class="ghost"
        :animation="200"
        @add="(evt) => onContainerDragAdd(evt, widget.widgetList)"
        @update="onContainerDragUpdate"
        :move="checkContainerMove">
        <template #item="{ element: subWidget, index: swIdx }">
          <div class="form-widget-list">
            <template v-if="'container' === subWidget.category">
              <component :is="subWidget.type + '-widget'"
                :widget="subWidget"
                :designer="designer"
                :key="subWidget.id"
                :parent-list="widget.widgetList"
                :index-of-parent-list="swIdx"
                :parent-widget="parentWidget"></component>
            </template>
            <template v-else>
              <component :is="subWidget.type + '-widget'"
                :field="subWidget"
                :designer="designer"
                :key="subWidget.id"
                :parent-list="widget.widgetList"
                :index-of-parent-list="swIdx"
                :parent-widget="parentWidget"
                :design-state="true"></component>
            </template>
          </div>
        </template>
      </draggable>
    </el-card>
    <span v-show="false"
      class="dialog-info">
      <VfIcon name="info"
        class="info"
        style="font-size: 16px;color: var(--el-color-primary);"
        @click="showDialog(true)" />
    </span>
    <div ref="dialogContentRef">
      <RKDialog ref="rkDialogRef"
        :visible="visible"
        :="widget.options.dialogConfig"
        :className="widget.options.dialogConfig.customClass"
        :showHeader="widget.options.dialogConfig.headerConfig.showHeader"
        :showFooter="widget.options.dialogConfig.footerConfig.showFooter"
        :title="widget.options.dialogConfig.headerConfig.title"
        @confirm="onConfirm"
        @open="onDialogOpened"
        @close="showDialog(false)"
        @cancel="onCancel">
      </RKDialog>
    </div>
  </container-wrapper>
</template>

<script>
import i18n from "@/utils/i18n"
import containerMixin from "@/components/form-designer/form-widget/container-widget/containerMixin"
import ContainerWrapper from "@/components/form-designer/form-widget/container-widget/container-wrapper"
import FieldComponents from '@/components/form-designer/form-widget/field-widget/index'
import refMixinDesign from "@/components/form-designer/refMixinDesign"
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { RKDialog } from '@/components/vf-dialog'
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";
import XEUtils from "xe-utils"

export default {
  name: "dialog-widget",
  componentName: 'FieldWidget',
  mixins: [i18n, refMixinDesign, fieldMixin, containerMixin,],
  inject: ['refList'],
  components: {
    ContainerWrapper,
    ...FieldComponents,
    ArrowDown,
    ArrowUp,
    RKDialog
  },
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
  },
  data() {
    return {
      visible: false,
    }
  },
  computed: {
    dialogRef() {
      return this.$refs['rkDialogRef']
    },
    cardRef() {
      return this.$refs['cardRef']
    },
    dialogContentRef() {
      return this.$refs['dialogContentRef']
    },
    selected() {
      return this.widget.id === this.designer.selectedId
    },

    customClass() {
      return this.widget.options.customClass || ''
    },

    // 判断是否在同步布局组件内
    isInLayoutSync() {
      let parent = this.parentWidget;
      let depth = 0;
      while (parent && depth < 10) {
        if (parent.type === 'layout-sync') {
          return true;
        }
        // 特殊处理：如果父组件是tab，继续检查tab的父组件
        if (parent.type === 'tab') {
          if (parent.parentWidget) {
            parent = parent.parentWidget;
            depth++;
            continue;
          } else {
            break;
          }
        }
        parent = parent.parentWidget;
        depth++;
      }
      return false;
    },
    // 判断元素是否来自同步布局的左侧
    isSyncFromLeft() {
      // 检查元素是否有位置标识
      if (this.widget && this.widget.hasOwnProperty('_layoutPosition')) {
        const isFromLeft = this.widget._layoutPosition === 'left';
        return isFromLeft;
      }
      return false;
    }
  },
  created() {
    this.initRefList()
  },
  mounted() {
  },
  methods: {
    selectWidget(widget) {
      this.designer.setSelected(widget)
    },

    initRefList() {
      if ((this.widget.type == 'dialog') && !!this.widget.options.name) {
        this.refList[this.widget.options.name] = this
      }
    },

    onContainerDragAdd(evt, subList) {
      const newIndex = evt.newIndex
      if (!!subList[newIndex]) {
        this.designer.setSelected(subList[newIndex])
      }
      this.designer.emitHistoryChange()
    },

    onContainerDragUpdate() {
      this.designer.emitHistoryChange()
    },

    handleClone(original) {
      if (this.designer && this.designer.copyNewFieldWidget && original.category === 'field') {
        return this.designer.copyNewFieldWidget(original);
      } else if (this.designer && this.designer.copyNewContainerWidget && original.category === 'container') {
        return this.designer.copyNewContainerWidget(original);
      }
      // 如果没有 designer 或其他情况，返回原始对象
      return original;
    },
    checkContainerMove(evt) {
      return this.designer.checkWidgetMove(evt)
    },
    addElement() {
      var targetElement = this.dialogContentRef.querySelector('.vxe-modal--content')
      const cardEl = this.$refs.cardRef.$el || this.$refs.cardRef
      if (targetElement && cardEl) {
        const clonedContent = XEUtils.clone(cardEl, true)
        clonedContent.style.display = 'block'
        clonedContent.style.height = '100%'
        targetElement.replaceChildren(clonedContent)
      }
    },
    removeElement() {
      var targetElement = this.dialogContentRef.querySelector('.vxe-modal--content')
      const cardEl = this.$refs.cardRef.$el || this.$refs.cardRef
      if (targetElement && cardEl) {
        const clonedContent = XEUtils.clone(cardEl, true)
        clonedContent.style.display = 'none'
        clonedContent.style.height = '0px'
        targetElement.replaceChildren(clonedContent)
      }
    },
    showDialog(show = true) {
      if (show) {
        this.dialogRef.open()
      } else {
        this.dialogRef.close()
        this.$nextTick(() => {
          this.removeElement()
        })
      }
    },
    onConfirm() {
      this.handleDialogWidgetClick({}, 'onConfirm')
    },
    onCancel() {
      this.handleDialogWidgetClick({}, 'onCancel')
    },
    onDialogOpened() {
      this.$nextTick(() => {
        this.addElement()
      })
      this.handleDialogWidgetClick({}, 'onOpened')
    },
  }
}
</script>

<style lang="scss" scoped>
.card-container {
  margin: 6px 0;
  //border: 1px dashed #336699;
  :deep(.el-card__header) {
    padding: 8px 12px;
    background-color: #f6f6f6;
    border-bottom: 1px solid #e9e9e9;
  }
  :deep(.el-card__body) {
    height: 100%;
  }
  .form-widget-list {
    //border: 1px dashed #336699;
    margin: 3px;
    min-height: 28px;
  }
}

.card-container.selected {
  outline: 2px solid $--color-primary !important;
  outline-offset: 2px;
}

.card-container.folded {
  :deep(.el-card__body) {
    display: none;
  }
}

.float-right {
  float: right;
}

.clear-fix {
  zoom: 1;

  &::after {
    clear: both;
    content: "";
    display: block;
    height: 0;
    visibility: hidden;
  }
}
.dialog-info {
  position: relative;
  .info {
    position: relative;
    top: -4px;
    cursor: pointer;
  }
}
</style>